/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.wephone.Student.huanxin.adapter;

import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMGroupManager;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.wephone.Student.R;
import com.wephone.Student.bean.BaseResponse;
import com.wephone.Student.bean.EditMyInfoResponse;
import com.wephone.Student.bean.data.GroupInvite;
import com.wephone.Student.bean.data.UserInfoData;
import com.wephone.Student.huanxin.activity.ChatHistoryActivity;
import com.wephone.Student.huanxin.activity.NewFriendsMsgActivity;
import com.wephone.Student.huanxin.db.InviteMessgeDao;
import com.wephone.Student.huanxin.domain.InviteMessage;
import com.wephone.Student.huanxin.domain.InviteMessage.InviteMesageStatus;
import com.wephone.Student.network.HttpClient;
import com.wephone.Student.network.MyResponseHandler;
import com.wephone.Student.ui.BaseActivity;
import com.wephone.Student.ui.EditMyInfoActivity;
import com.wephone.Student.util.Constants;
import com.wephone.Student.util.ImageLoaderUtil;
import com.wephone.Student.util.ShareReferenceUtil;


public class NewFriendsMsgAdapter extends ArrayAdapter<GroupInvite> {

	private Context context;
	//private InviteMessgeDao messgeDao;
	private List<GroupInvite> data;

	public NewFriendsMsgAdapter(Context context, int textViewResourceId, List<GroupInvite> objects) {
		super(context, textViewResourceId, objects);
		this.context = context;
		this.data = objects;
		//messgeDao = new InviteMessgeDao(context);
	}
	private DisplayImageOptions options = new DisplayImageOptions.Builder()
    .showStubImage(R.drawable.default_user_logo)
    .showImageOnFail(R.drawable.default_user_logo)
    .bitmapConfig(Bitmap.Config.ARGB_8888)
    .cacheInMemory()
    .cacheOnDisc()
    .displayer(new RoundedBitmapDisplayer(1000))
    .build();
	
	public void setData(List<GroupInvite> dGroupInvites){
		this.data = dGroupInvites;
	}
	@Override
	public GroupInvite getItem(int position)
	{
		if(this.data!=null&&this.data.size()>0){
			return this.data.get(position);
		}else{
			return null;
		}
	}
	
	@Override
	public int getCount(){
		return this.data.size();
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final ViewHolder holder;
		if (convertView == null) {
			holder = new ViewHolder();
			convertView = View.inflate(context, R.layout.row_invite_msg, null);
			holder.avator = (ImageView) convertView.findViewById(R.id.avatar);
			holder.reason = (TextView) convertView.findViewById(R.id.message);
			holder.name = (TextView) convertView.findViewById(R.id.name);
			holder.status = (Button) convertView.findViewById(R.id.user_state);
			holder.status_no = (Button) convertView.findViewById(R.id.user_state_no);
			holder.groupContainer = (LinearLayout) convertView.findViewById(R.id.ll_group);
			holder.groupname = (TextView) convertView.findViewById(R.id.tv_groupName);
			// holder.time = (TextView) convertView.findViewById(R.id.time);
			convertView.setTag(holder);
		} else {
			holder = (ViewHolder) convertView.getTag();
		}
		
		String str1 = "已同意你的好友请求";
		String str2 = "同意";
		
		String str3 = "邀请您加入群 ";
		String str4 = "申请加入群 ";
		String str5 = "已同意";
		String str6 = "已拒绝";
		final GroupInvite msg = data.get(position);
		if (msg != null) {
			
			holder.groupContainer.setVisibility(View.GONE);
			
			
			holder.reason.setText(msg.getContent());
			
			
			// holder.time.setText(DateUtils.getTimestampString(new
			// Date(msg.getTime())));
			/*
			if (msg.getStatus() == InviteMesageStatus.BEAGREED) {
				holder.status.setVisibility(View.INVISIBLE);
				holder.status_no.setVisibility(View.INVISIBLE);
				holder.reason.setText(str1);
			} else
			*/	
			//if (msg.getStatus() == InviteMesageStatus.BEINVITEED || msg.getStatus() == InviteMesageStatus.BEAPPLYED) {
				holder.status.setVisibility(View.VISIBLE);
				holder.status.setEnabled(true);
				holder.status.setTextColor(context.getResources().getColor(R.color.orange));
				holder.status_no.setVisibility(View.VISIBLE);
				holder.status_no.setEnabled(true);
				holder.status_no.setTextColor(context.getResources().getColor(R.color.orange));
				holder.status.setBackgroundResource(R.drawable.button_bg);
				holder.status.setText(str2);
				if(msg.getInvite().equals("0")){//被邀请
					if (msg.getContent() == null) {
						// 如果没写理由
						holder.reason.setText(str3+msg.getGroupname());
					}else{
						holder.reason.setText(str3+ msg.getGroupname()+" :"+msg.getContent());
					}
				}else{ //入群申请
					if (TextUtils.isEmpty(msg.getContent())) {
						holder.reason.setText(str4 + msg.getGroupname());
					}else{
						holder.reason.setText(str4 + msg.getGroupname()+" :"+msg.getContent());
					}
				}
				// 设置点击事件
				holder.status.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// 同意别人发的好友请求
						
						acceptInvitation(holder.status, msg,1);
					}
				});
				
				// 设置点击事件
				holder.status_no.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// 同意别人发的好友请求
						acceptInvitation(holder.status_no, msg,2);
					}
				});

			// 设置用户头像
			String pushUserStr = ShareReferenceUtil
					.getPushUserInfoJson(context);
			Gson gson = new Gson();
			List<UserInfoData> userInfoList = gson.fromJson(pushUserStr,
							new TypeToken<List<UserInfoData>>() {
							}.getType());
			UserInfoData nowFrom = new UserInfoData();
			for(UserInfoData userInfo:userInfoList){
				if(msg.getFrom_user_id().equals(userInfo.getuId())){
					nowFrom = userInfo;
					break;
				}
			}
			if(nowFrom.getuName()!=null){
				holder.name.setText(nowFrom.getuName());
				String endStr = nowFrom.getuIcon().substring(nowFrom.getuIcon().lastIndexOf("."));
				ImageLoaderUtil.getInstance(context, R.drawable.default_avatar).displayImage(Constants.IMAGE_PHOTO_SERVER_PATH+nowFrom.getuIcon().replace(endStr, "_150_150"+endStr), holder.avator, options);
				
			}else{
				holder.name.setText(msg.getFrom_user_id());
				
			}
			
		}

		return convertView;
	}

	
	/**
	 * 同意好友请求或者群申请
	 * 
	 * @param button
	 * @param username
	 */
	private void acceptInvitation(final Button button, final GroupInvite msg,final int ok) {
		final ProgressDialog pd = new ProgressDialog(context);
		String str1 = "正在操作...";
		final String str2 = "已同意";
		final String str3 = "同意失败:";
		pd.setMessage(str1);
		pd.setCanceledOnTouchOutside(false);
		pd.show();
		button.setEnabled(false);
		button.setTextColor(context.getResources().getColor(R.color.gray_normal));
		new Thread(new Runnable() {
			public void run() {
				// 调用sdk的同意方法
				try {
					  //同意加群申请
					  //  EMGroupManager.getInstance().acceptApplication(msg.getFrom(), msg.getGroupId());
						RequestParams params = new RequestParams();
						if(msg.getInvite().equals("0")){
							params.put("uId", msg.getTo_user_id());
						}else{
							params.put("uId", msg.getFrom_user_id());
						}
						params.put("id", msg.getId());
						params.put("group_id", msg.getGroupid());
						if(ok==1){
							HttpClient.getInstance().get(Constants.API_AGREE_ADD_CHART, params, new MyResponseHandler((Activity)context,BaseResponse.class){
								@Override
								public void onSuccess(String result) {
									super.onSuccess(result);
									((Activity) context).runOnUiThread(new Runnable() {
										@Override
										public void run() {
											pd.dismiss();
											// 更新db
											NewFriendsMsgActivity.s_instance.refresh();
											ChatHistoryActivity.needRefresh = true;
										}
									});
								}
							} );
						}else{
							HttpClient.getInstance().get(Constants.API_REFUSE_ADD_CHART, params, new MyResponseHandler((Activity)context,BaseResponse.class){
								@Override
								public void onSuccess(String result) {
									//super.onSuccess(result);
									((Activity) context).runOnUiThread(new Runnable() {
										@Override
										public void run() {
											pd.dismiss();
											// 更新db
											NewFriendsMsgActivity.s_instance.refresh();
											ChatHistoryActivity.needRefresh = true;
										}
									});
								}
							} );
						}
					
					}
				 catch (final Exception e) {
					((Activity) context).runOnUiThread(new Runnable() {
						@Override
						public void run() {
							pd.dismiss();
							Toast.makeText(context, str3 + e.getMessage(), 1).show();
						}
					});
				 }
				}
		}).start();
	}

	private static class ViewHolder {
		ImageView avator;
		TextView name;
		TextView reason;
		Button status;
		Button status_no;
		LinearLayout groupContainer;
		TextView groupname;
		// TextView time;
	}

}
